package com.pengshun.modules.api.quartz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.pengshun.modules.api.coal.domain.CoalRecord;
import com.pengshun.modules.api.coal.repository.CoalRecordRepository;
import com.pengshun.modules.api.coal.util.DateUitl;
import com.pengshun.modules.api.mapper.PsCoalMapper;
import com.pengshun.modules.api.quartz.service.QuartzService;
import com.pengshun.modules.api.statistical.service.dto.CoalStatisticalDto;
import com.pengshun.modules.api.statistical.service.mapstruct.CoalStatisticalTodo;
import com.pengshun.modules.api.statistical.service.repository.CoalStatisticalRepository;
import com.pengshun.modules.common.BaseResult;
import com.pengshun.modules.domain.CoalStatistical;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author luoligang
 * @create 2021/1/25
 */
@Service
@RequiredArgsConstructor
public class QuartzServiceImpl implements QuartzService {

    private final PsCoalMapper coalMapper;

    private final CoalRecordRepository coalRecordRepository;

    private final CoalStatisticalRepository coalStatisticalRepository;
    private final CoalStatisticalTodo coalStatisticalTodo;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateCoalStatistical(Long coalId) {
        //待维护集合
        List<CoalStatisticalDto> dtos = new ArrayList<>();
        //查询新的煤炭记录
        List<CoalRecord> list = coalRecordRepository.findByCoalIdAndIsnewOrderByUpdateTime(coalId, 1);
        List<CoalStatistical> statistical = coalStatisticalRepository.findByCoalIdOrderByPriceDateDesc(coalId);
        if (list.size() == 1 && statistical.size() > 0) {
            if (list.get(0).getUpdateTime().getTime() > statistical.get(0).getPriceDate().getTime()) {
                CoalRecord r = list.get(0);
                CoalStatisticalDto dd = coalStatisticalTodo.toDto(statistical.get(0));
                setPrice(dd.getNowPrice(), dd.getPriceDate(), coalId, dd, dtos, r);
                r.setIsnew(0);
                coalRecordRepository.save(r);
                dd.setIsold(1);
                coalStatisticalRepository.saveAll(coalStatisticalTodo.toEntity(dtos));
                return new BaseResult(0);
            }
        }
        if (list.size() > 0) {
            //删除维护表数据
            coalStatisticalRepository.deleteByCoalId(coalId);
            //查询所有记录
            list = coalRecordRepository.findByCoalIdOrderByUpdateTime(coalId);
            //标记是否第一次
            int i = 0;
            for (int j = 0; j < list.size(); j++) {
                list.get(j).setIsnew(0);
                //当前记录
                CoalRecord r = list.get(j);

                if (i == 1) {
                    //上次记录
                    CoalRecord re = list.get(j - 1);
                    //上次统计数据
                    CoalStatisticalDto dd = dtos.get(dtos.size() - 1);
                    setPrice(re.getCoalPrice(), re.getUpdateTime(), coalId, dd, dtos, r);

                } else {
                    CoalStatisticalDto dto = new CoalStatisticalDto(coalId, r.getCoalName(), r.getCoalMineName(), new BigDecimal(0), r.getCoalPrice(), new BigDecimal(0),
                            "+" + r.getCoalPrice(), "100%", "+" + r.getCoalPrice(), "100%",
                            "+" + r.getCoalPrice(), "100%", r.getUpdateTime(), 1L, 1, new Date());
                    dtos.add(dto);
                }

                i = 1;
            }
            //更新状态
            if (list.size() > 0) {
                coalRecordRepository.saveAll(list);
            }
            if (dtos.size() > 0) {
                coalStatisticalRepository.saveAll(coalStatisticalTodo.toEntity(dtos));
            }
        }
        return new BaseResult(0);
    }

    private void setPrice(BigDecimal price, Date time, Long coalId, CoalStatisticalDto dd, List<CoalStatisticalDto> dtos, CoalRecord r) {
        //上次记录

        //判断当前日期和上期日期天数 维护数据
        List<Date> dates = DateUitl.getBetweenDate(time, r.getUpdateTime());
        for (Date d : dates) {

            CoalStatisticalDto newc = new CoalStatisticalDto(dd.getCoalId(), dd.getCoalName(), dd.getMineMouthName(), dd.getStageiaPrice(), dd.getNowPrice(), dd.getLastYearPrice(),
                    dd.getRingThan(), dd.getRingThanPercent(), dd.getSameThan(), dd.getSameThanPercent(), dd.getRiseAndFall(), dd.getRiseAndFallPercent(), dd.getPriceDate(), dd.getUserId(), 1, dd.getCreateTime());
            newc.setColor(3);
            newc.setRingThan("0.00");
            newc.setRingThanPercent("0.00%");
            newc.setRingThan("0.00");
            newc.setRingThanPercent("0.00%");
            newc.setRiseAndFall("0.00");
            newc.setRiseAndFallPercent("0.00%");
            newc.setStageiaPrice(newc.getNowPrice());
            newc.setPriceDate(d);
            newc.setIsold(0);
            dtos.add(newc);
        }
        //环比值
        BigDecimal ring = r.getCoalPrice().subtract(price);
        int iii = ring.compareTo(new BigDecimal(0));
//                i=0:表示bigDecimal的值  等于 0
//                i=1:表示bigDecimal的值与 大于0
//                i=-1:表示bigDecimal的值与 小于 0
        //环比率
        BigDecimal ThanPercent = ring.multiply(new BigDecimal(100));

        Integer color = 1;
        String ringThan = "";
        String ringThanPercent = "";
        if(price.compareTo(BigDecimal.ZERO)==0){
            CoalStatisticalDto dto = new CoalStatisticalDto(coalId, r.getCoalName(), r.getCoalMineName(), price, r.getCoalPrice(), new BigDecimal(0),
                    "0.00", "0.00%", "+" + price, "0.00%", "0.00", "0.00%", r.getUpdateTime(), 1L, 1, new Date());
            dtos.add(dto);
        }else {
            if (iii == 0) {
                ringThan = "0.00";
                ringThanPercent = "0.00%";
                color = 3;
            } else if (iii < 0) {
                ThanPercent = ThanPercent.divide(price, 2, BigDecimal.ROUND_HALF_UP);
                ringThan = "" + ring;
                ringThanPercent = ThanPercent + "%";
                color = 2;
            } else {
                ThanPercent = ThanPercent.divide(price, 2, BigDecimal.ROUND_HALF_UP);
                ringThan = "+" + ring;
                ringThanPercent = ThanPercent + "%";
            }
            CoalStatisticalDto dto = new CoalStatisticalDto(coalId, r.getCoalName(), r.getCoalMineName(), price, r.getCoalPrice(), new BigDecimal(0),
                    ringThan, ringThanPercent, "+" + r.getCoalPrice(), "100%", ringThan, ringThanPercent, r.getUpdateTime(), 1L, 1, new Date());
            dtos.add(dto);
        }

    }

    @Override
    public BaseResult updateCoalSameStatistical(Long coalId) {
        List<CoalStatistical> list = coalStatisticalRepository.findByCoalIdOrderByPriceDateDesc(coalId);
        List<CoalStatistical> newList = new ArrayList<>();
        List<CoalStatistical> waitUpdates = new ArrayList<>();
        newList.addAll(list);
        for (CoalStatistical c : list) {
            Date date = c.getPriceDate();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            ////当前时间减去一年，即一年前的时间
            calendar.add(Calendar.YEAR, -1);
            Date lastYear = calendar.getTime();

            for (CoalStatistical n : list) {
                if (n.getPriceDate().getTime() == lastYear.getTime()) {
                    CoalStatistical statistical = new CoalStatistical();
                    BeanUtil.copyProperties(c, statistical);
                    //同比
                    BigDecimal same = c.getNowPrice().subtract(n.getNowPrice());
                    int iii = same.compareTo(new BigDecimal(0));
//                  i=0:表示bigDecimal的值  等于 0
//                  i=1:表示bigDecimal的值与 大于0
//                  i=-1:表示bigDecimal的值与 小于 0
                    //同比率
                    BigDecimal samePercent = same.multiply(new BigDecimal(100));

                    Integer color = 1;
                    String sameThan = "";
                    String sameThanPercent = "";
                    if (iii == 0) {
                        sameThan = "0.00";
                        sameThanPercent = "0.00%";
                        color = 3;
                    } else if (iii < 0) {
                        samePercent = samePercent.divide(n.getNowPrice(), 2, BigDecimal.ROUND_HALF_UP);
                        sameThan = "" + same;
                        sameThanPercent = samePercent + "%";
                        color = 2;
                    } else {
                        samePercent = samePercent.divide(n.getNowPrice(), 2, BigDecimal.ROUND_HALF_UP);
                        sameThan = "+" + same;
                        sameThanPercent = samePercent + "%";
                    }
                    statistical.setSameThan(sameThan);
                    statistical.setSameThanPercent(sameThanPercent);
                    statistical.setLastYearPrice(n.getNowPrice());
                    waitUpdates.add(statistical);
                }
            }
        }
        if (waitUpdates.size() > 0 ){
            coalStatisticalRepository.saveAll(waitUpdates);
        }
        return new BaseResult(0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResult updateAllStatistical(Long coalId) {
        //待维护集合
        List<CoalStatisticalDto> dtos = new ArrayList<>();
        //查询新的煤炭记录
        List<CoalRecord> list = coalRecordRepository.findByCoalIdAndIsnewOrderByUpdateTime(coalId, 1);
        List<CoalStatistical> statistical = coalStatisticalRepository.findByCoalIdOrderByPriceDateDesc(coalId);
        if (list.size() == 1 && statistical.size() > 0) {
            if (list.get(0).getUpdateTime().getTime() > statistical.get(0).getPriceDate().getTime()) {
                CoalRecord r = list.get(0);
                CoalStatisticalDto dd = coalStatisticalTodo.toDto(statistical.get(0));
                setPrice(dd.getNowPrice(), dd.getPriceDate(), coalId, dd, dtos, r);
                r.setIsnew(0);
                coalRecordRepository.save(r);
                dd.setIsold(1);
                coalStatisticalRepository.saveAll(coalStatisticalTodo.toEntity(dtos));
                return new BaseResult(0);
            }
        }
        if (list.size() > 0) {
            //删除维护表数据
            coalStatisticalRepository.deleteByCoalId(coalId);
            //查询所有记录
            list = coalRecordRepository.findByCoalIdOrderByUpdateTime(coalId);
            //标记是否第一次
            int i = 0;
            for (int j = 0; j < list.size(); j++) {
                list.get(j).setIsnew(0);
                //当前记录
                CoalRecord r = list.get(j);

                if (i == 1) {
                    //上次记录
                    CoalRecord re = list.get(j - 1);
                    //上次统计数据
                    CoalStatisticalDto dd = dtos.get(dtos.size() - 1);
                    setPrice(re.getCoalPrice(), re.getUpdateTime(), coalId, dd, dtos, r);

                } else {
                    CoalStatisticalDto dto = new CoalStatisticalDto(coalId, r.getCoalName(), r.getCoalMineName(), new BigDecimal(0), r.getCoalPrice(), new BigDecimal(0),
                            "+" + r.getCoalPrice(), "100%", "+" + r.getCoalPrice(), "100%",
                            "+" + r.getCoalPrice(), "100%", r.getUpdateTime(), 1L, 1, new Date());
                    dtos.add(dto);
                }

                i = 1;
            }
            //更新状态
            if (list.size() > 0) {
                coalRecordRepository.saveAll(list);
            }
            if (dtos.size() > 0) {
                coalStatisticalRepository.saveAll(coalStatisticalTodo.toEntity(dtos));
            }
        }
        List<CoalStatistical> lists = coalStatisticalRepository.findByCoalIdOrderByPriceDateDesc(coalId);
        List<CoalStatistical> newList = new ArrayList<>();
        List<CoalStatistical> waitUpdates = new ArrayList<>();
        newList.addAll(lists);
        for (CoalStatistical c : lists) {
            Date date = c.getPriceDate();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            ////当前时间减去一年，即一年前的时间
            calendar.add(Calendar.YEAR, -1);
            Date lastYear = calendar.getTime();

            for (CoalStatistical n : lists) {
                if (n.getPriceDate().getTime() == lastYear.getTime()) {
                    CoalStatistical statisticals = new CoalStatistical();
                    BeanUtil.copyProperties(c, statisticals);
                    //同比
                    BigDecimal same = c.getNowPrice().subtract(n.getNowPrice());
                    int iii = same.compareTo(new BigDecimal(0));
//                  i=0:表示bigDecimal的值  等于 0
//                  i=1:表示bigDecimal的值与 大于0
//                  i=-1:表示bigDecimal的值与 小于 0
                    //同比率
                    BigDecimal samePercent = same.multiply(new BigDecimal(100));

                    Integer color = 1;
                    String sameThan = "";
                    String sameThanPercent = "";
                    if (iii == 0) {
                        sameThan = "0.00";
                        sameThanPercent = "0.00%";
                        color = 3;
                    } else if (iii < 0) {
                        samePercent = samePercent.divide(n.getNowPrice(), 2, BigDecimal.ROUND_HALF_UP);
                        sameThan = "" + same;
                        sameThanPercent = samePercent + "%";
                        color = 2;
                    } else {
                        samePercent = samePercent.divide(n.getNowPrice(), 2, BigDecimal.ROUND_HALF_UP);
                        sameThan = "+" + same;
                        sameThanPercent = samePercent + "%";
                    }
                    statisticals.setSameThan(sameThan);
                    statisticals.setSameThanPercent(sameThanPercent);
                    statisticals.setLastYearPrice(n.getNowPrice());
                    waitUpdates.add(statisticals);
                }
            }
        }
        if (waitUpdates.size() > 0 ){
            coalStatisticalRepository.saveAll(waitUpdates);
        }
        return new BaseResult(0);
    }
}
